package com.cdtu.store.item.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cdtu.store.common.entity.SpecParamEntity;
import com.cdtu.store.common.utils.PageUtils;
import com.cdtu.store.common.utils.Query;
import com.cdtu.store.item.dao.SpecGroupDao;
import com.cdtu.store.common.entity.SpecGroupEntity;
import com.cdtu.store.item.service.SpecGroupService;
import com.cdtu.store.item.service.SpecParamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;


@Service("specGroupService")
public class SpecGroupServiceImpl extends ServiceImpl<SpecGroupDao, SpecGroupEntity> implements SpecGroupService {

    @Autowired
    private SpecParamService specParamService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpecGroupEntity> page = this.page(
                new Query<SpecGroupEntity>().getPage(params),
                new QueryWrapper<SpecGroupEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params, Long cid) {
        if (cid == 0) {
            IPage<SpecGroupEntity> page = this.page(new Query<SpecGroupEntity>().getPage(params),
                    new QueryWrapper<SpecGroupEntity>()
            );
            return new PageUtils(page);
        } else {
            String key = (String) params.get("key");
            QueryWrapper<SpecGroupEntity> wrapper = new QueryWrapper<SpecGroupEntity>().eq("cid", cid);
            if (!StringUtils.isEmpty(key)) {
                wrapper.and((obj) -> {
                    obj.like("name", key);
                });
            }
            IPage<SpecGroupEntity> page = this.page(new Query<SpecGroupEntity>().getPage(params), wrapper);
            return new PageUtils(page);
        }
    }

    @Override
    public void updateDetail(SpecGroupEntity specGroup) {
        this.updateById(specGroup);
        if(!StringUtils.isEmpty(specGroup.getName())){
            specParamService.updateParam(specGroup.getId(),specGroup.getName());
            //TODO 更新其他表的冗余信息
        }
    }

    @Override
    public List<SpecGroupEntity> querySpecsByCid(Long cid) {
        List<SpecGroupEntity> groups = this.list(new QueryWrapper<SpecGroupEntity>().eq("cid", cid));
        groups.forEach(group ->{
            group.setParams(this.specParamService.list(new QueryWrapper<SpecParamEntity>().eq("group_id",group.getId())));
        });
        return groups;
    }

}